package com.atguigu.day04;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Felix
 * @date 2024/4/2
 * 当前案例演示了将流中数据写到kafka主题
 * 要想保证写到kafka的数据的精准一次，需要做如下的设置
 *      开启检查点
 *      .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
 *      .setTransactionalIdPrefix("xxxx")
 *      .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000 + "")
 *      在消费端，将事务的隔离级别设置为读已提交  .setProperty("ConsumerConfig.ISOLATION_LEVEL_CONFIG","read_committed")
 */
public class Flink09_Sink_Kafka {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.将流中数据写到kafka主题中
        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
                .setBootstrapServers("hadoop102:9092")
                .setRecordSerializer(
                        KafkaRecordSerializationSchema.builder()
                                .setTopic("first")
                                .setValueSerializationSchema(new SimpleStringSchema())
                                .build()
                )
                //.setDeliveryGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
                //.setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                //.setTransactionalIdPrefix("xxxx")
                //.setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000 + "")
                .build();


        socketDS.print();
        socketDS.sinkTo(kafkaSink);
        //TODO 4.提交作业
        env.execute();
    }
}
